import ViewUI from 'view-design';
import { store, router, interceptors } from '_/support'
import settings from "@/settings";
import { getToken } from "_/utils/auth";
const PAGE_HOME = settings.route.index;
const PAGE_LOGIN = settings.route.login;

const DEBUG_TITLE = `background:#876cf6 ; padding: 3px; border-radius: 3px 0 0 3px;  color: #fff`;
const DEBUG_TEXT = `background:#41b883 ; padding: 3px; border-radius: 0 3px 3px 0;  color: #fff`;

export default {
  install(Vue) {
    console.debug(`[debug] plugin - permissions 注册权限管理插件`);
    // *** 移除通过行为特性控制权限机制
    // 处理登录跳转
    const SECURITY = '%c身份验证%c';

    settings.injections.permissions = () => {
      return store.getters.permissions
    };
    /** 处理 登录鉴权 */
    router.beforeEach((to, from, next) => {
      console.debug(`${SECURITY}${from.name} -> ${to.name}`, DEBUG_TITLE, DEBUG_TEXT);
      const token = getToken();
      if (unwantedAuthorized(to)) {
        console.debug(`${SECURITY}无权限控制 -> 跳过`, DEBUG_TITLE, DEBUG_TEXT);
        next();
      } else {
        if (!token && to.name !== PAGE_LOGIN) {
          console.debug(`${SECURITY}未登录且要跳转的页面不是登录页 -> 跳转至登录页`, DEBUG_TITLE, DEBUG_TEXT);
          // 未登录且要跳转的页面不是登录页 -> 跳转至登录页
          next({ name: PAGE_LOGIN })
        } else if (!token && to.name === PAGE_LOGIN) {
          // 未登陆且要跳转的页面是登录页 -> 跳转
          console.debug(`${SECURITY}未登陆且要跳转的页面是登录页 -> 通过 `, DEBUG_TITLE, DEBUG_TEXT);
          next()
        } else if (token && to.name === PAGE_LOGIN) {
          // 已登录且要跳转的页面是登录页
          // 验证请求参数
          // http://domain/#/login?redirect=http://domain/&logout
          const { redirect, type } = to.query;
          if (type == 'logout') {
            console.debug(`${SECURITY}已登录且要跳转的页面是登录页 & type=logout -> 注销`, DEBUG_TITLE, DEBUG_TEXT);
            store.dispatch('logout', to.query);
          } else if (redirect) {
            console.debug(`${SECURITY}已登录且要跳转的页面是登录页 & redirect -> 回调`, DEBUG_TITLE, DEBUG_TEXT);
            window.location = `${redirect}?token=${token}`;
          } else {
            // -> 跳转至首页
            console.debug(`${SECURITY}已登录且要跳转的页面是登录页 -> 通过`, DEBUG_TITLE, DEBUG_TEXT);
            next({ name: PAGE_HOME })
          }
        } else {
          console.debug(`${SECURITY}已登录 -> 身份验证`, DEBUG_TITLE, DEBUG_TEXT);
          store.dispatch('authentication')
            .then(() => {
              console.debug(`${SECURITY}身份验证 -> 通过`, DEBUG_TITLE, DEBUG_TEXT);
              next()
            })
            .catch(error => {
              console.debug(`${SECURITY}身份验证 -> 未通过 & ${error.message}`, DEBUG_TITLE, DEBUG_TEXT);
              ViewUI.Notice.error(error);
              store.dispatch('logout');
            });
        }
      }
    });
    /** 处理 访问鉴权 */
    router.beforeEach((to, from, next) => {
      if (to.name === PAGE_HOME) {
        next();
        return;
      }
      const routePowers = [];
      const routeName = to.name;
      const permissions = store.getters.permissions;
      const powers = to.meta.powers || [];
      powers.forEach(power => {
        const permissionCode = `${routeName}-${power.code}`;
        if (unwantedAuthorized(to) || permissions.length === 0 || permissions.indexOf(permissionCode) > -1) {
          routePowers.push(power.code);
        }
      });
      store.dispatch('setRoutePowers', routePowers);
      next();
    });
    // 注册全局拦截器
    interceptors.request.use(config => {
      let token = getToken();
      if (token) {
        if (config.method == 'post') {
          config.data = { ...config.data, token };
        } else if (config.method == 'get') {
          config.params = { ...config.params, token };
        }
      }
      return config;
    });
    interceptors.response.use(response => {
      const result = response.data;
      switch (result.ret) {
        case 0:
          return Promise.resolve(result);
        case -5:
          // ret=-5表示token无效或者已经过期
          // 需要重新登录
          store.dispatch("logout", { redirect: router.app.$route.name });
          // eslint-disable-next-line
          return Promise.reject({ ret: -5, title: "身份验证失败", desc: result.msg });
        default:
          let { ret, msg, title, desc, data } = result;
          if (data) {
            let msgs = [];
            for (var property in data) {
              msgs.push(data[property]);
            }
            title = msg;
            desc = msgs.join('<br/>');
          } else {
            title = "请求失败";
            desc = msg;
          }
          // eslint-disable-next-line
          return Promise.reject({ ret, title, desc });
      }
    });
    /**
     * 判断一个路由是否需要授权
     * @param {Object} route 需要判断的路由
     */
    const unwantedAuthorized = (route) => {
      return route.meta && route.meta.disablePermission
    }
    /**
     * 验证是否拥有权限
     * @param {string} permission 权限代码
     */
    Vue.prototype.$can = (permission) => {
      if (permission) {
        const { routePowers } = store.getters;
        if (routePowers) {
          return routePowers.indexOf(permission) > -1
        }
        return false;
      }

      return true;
    }
  }
}
